import { useEffect, useState } from "react";
import { HashRouter } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { useTranslation } from "react-i18next";
import Router from "./routers/router"
import { ConfigProvider } from "antd";
import AuthRouter from "./routers/utils/authRouter"
import type { RootState } from "./store";
import useTheme from './hooks/useTheme'
import { getBrowserLang } from './utils/utils'
import { setLanguage } from './store/modules/global'
import zhCN from 'antd/lib/locale/zh_CN'
import enUS from 'antd/lib/locale/en_US'
import type { SizeType } from "antd/lib/config-provider/SizeContext";

const App = () => {
  const { themeConfig, assemblySize, language } = useSelector(
    (state: RootState) => state.global
  )
  const [i18nLocale, setI18nLocale] = useState(zhCN)
  const dispatch = useDispatch()
  const { i18n } = useTranslation()

  // 全局使用主题
  useTheme(themeConfig);

  // 语言国际化
  const setAntdLanguage = () => {
    if (language && language === "zh") return setI18nLocale(zhCN);
    if (language && language == "en") return setI18nLocale(enUS);
    if (getBrowserLang() == "zh") return setI18nLocale(zhCN);
    if (getBrowserLang() == "en") return setI18nLocale(enUS);
  };

  useEffect(() => {
    i18n.changeLanguage(language || getBrowserLang())
    setAntdLanguage()
    dispatch(setLanguage(language || getBrowserLang()))
  }, [language])

  return (
   <HashRouter>
    <ConfigProvider locale={i18nLocale} componentSize={assemblySize as SizeType}>
      <AuthRouter>
        <Router />
      </AuthRouter>
    </ConfigProvider>
   </HashRouter>
  );
}

export default App;
